package code;

import java.util.Deque;
import java.util.LinkedList;


public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    public TreeNode createTree(Integer[] nums) {

        Deque<TreeNode> deque = new LinkedList<>();
        TreeNode root = new TreeNode(nums[0]);
        deque.push(root);
        int i = 1;
        while (!deque.isEmpty()) {
            if (i == nums.length) {
                return root;
            }
            TreeNode node = deque.getFirst();
            deque.removeFirst();
            if (nums[i] != null) {
                node.left = new TreeNode(nums[i]);
                deque.addLast(node.left);
            }
            i++;
            if (i == nums.length) {
                return root;
            }
            if (nums[i] != null) {
                node.right = new TreeNode(nums[i]);
                deque.addLast(node.right);
            }
            i++;
        }
        return root;
    }

    public void printTree(TreeNode root) {
        System.out.println(root.val);
        if (root.left != null) {
            printTree(root.left);
        }
        if (root.right != null) {
            printTree(root.right);
        }
    }


}
